#!/bin/bash

# 修复 Dockerfile 构建问题的脚本

set -e

GREEN='\033[0;32m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date '+%H:%M:%S')]${NC} $1"
}

log "🔧 修复 Dockerfile 构建问题..."

# 进入项目目录
cd /opt/jpom/projects/tetris-game

# 1. 修复 Dockerfile
log "📝 创建修复的 Dockerfile..."
cat > Dockerfile << 'EOF'
# 多阶段构建 - 构建阶段
FROM node:18-alpine AS builder

WORKDIR /app

# 复制 package 文件
COPY package*.json ./

# 安装所有依赖（包括开发依赖，构建需要 TypeScript）
RUN npm ci

# 复制源代码
COPY . .

# 构建项目
RUN npm run build

# 生产阶段 - 使用 Nginx 提供静态文件服务
FROM nginx:alpine

# 复制自定义 nginx 配置
COPY nginx.conf /etc/nginx/conf.d/default.conf

# 复制构建产物到 nginx 目录
COPY --from=builder /app/dist /usr/share/nginx/html

# 暴露端口
EXPOSE 80

# 启动 nginx
CMD ["nginx", "-g", "daemon off;"]
EOF

# 2. 创建 nginx.conf（如果不存在）
if [ ! -f nginx.conf ]; then
    log "📝 创建 nginx.conf..."
    cat > nginx.conf << 'EOF'
server {
    listen 80;
    server_name _;
    
    root /usr/share/nginx/html;
    index index.html;
    
    # 启用 gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
    
    # 静态文件缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # HTML 文件不缓存
    location ~* \.html$ {
        expires -1;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }
    
    # SPA 路由支持
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
}
EOF
fi

# 3. 更新构建脚本
log "📝 更新构建脚本..."
cat > simple-build.sh << 'EOF'
#!/bin/bash
set -e

CONTAINER_NAME="tetris-game"
IMAGE_NAME="tetris-game"
PORT="3000"

echo "🚀 开始构建部署..."

# 拉取最新代码
if [ -d ".git" ]; then
    echo "📥 拉取最新代码..."
    git pull origin main 2>/dev/null || git pull origin master 2>/dev/null || true
fi

# 停止旧容器
if docker ps -q -f name=${CONTAINER_NAME} | grep -q .; then
    echo "🛑 停止旧容器..."
    docker stop ${CONTAINER_NAME}
    docker rm ${CONTAINER_NAME}
fi

# 删除旧镜像
if docker images -q ${IMAGE_NAME} | grep -q .; then
    echo "🗑️ 删除旧镜像..."
    docker rmi ${IMAGE_NAME}
fi

# 构建新镜像
echo "🔨 构建镜像..."
docker build -t ${IMAGE_NAME} .

# 启动容器
echo "🚀 启动容器..."
docker run -d --name ${CONTAINER_NAME} --restart unless-stopped -p ${PORT}:80 ${IMAGE_NAME}

# 等待容器启动
echo "⏳ 等待容器启动..."
sleep 5

# 检查状态
if docker ps -f name=${CONTAINER_NAME} | grep -q ${CONTAINER_NAME}; then
    echo "✅ 部署成功！"
    echo "🌐 访问地址: http://82.157.51.127:${PORT}"
    echo "📊 容器状态: $(docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' -f name=${CONTAINER_NAME})"
else
    echo "❌ 部署失败，查看日志:"
    docker logs ${CONTAINER_NAME}
    exit 1
fi
EOF

chmod +x simple-build.sh

# 4. 测试构建
log "🧪 测试构建..."
echo "准备开始构建，这可能需要几分钟..."

# 执行构建
if ./simple-build.sh; then
    log "✅ 构建成功！"
    echo ""
    echo "🌐 访问地址:"
    echo "  游戏: http://82.157.51.127:3000"
    echo "  健康检查: http://82.157.51.127/health"
    echo ""
    echo "📊 容器状态:"
    docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' -f name=tetris-game
else
    log "❌ 构建失败，查看错误信息"
    echo ""
    echo "🔍 调试信息:"
    echo "  查看容器日志: docker logs tetris-game"
    echo "  查看镜像: docker images | grep tetris"
    echo "  重新构建: ./simple-build.sh"
fi

log "🎉 修复完成！"
